#include "typedef.h"
#include "os.h"
#include "os_tick.h"
#include "os_sys.h"
#include "protocol_bsp.h"


struct protocol_task_s
{
    SysTick_t tick;
    u32 heard_cnt;
};

static struct protocol_task_s protocol_task={.tick=0};


static void protocol_process(u8 * buff)
{
    u16 cmd=u8tou16(buff[4],buff[5]);
    u8 * data= &buff[6];
    u32 u32temp=0;
    switch(cmd)
    {
        case PRO_CMD_HEARTBEAT:
            u32temp = u8tou32(data[0],data[1],data[2],data[3]);
            protocol_task.heard_cnt=u32temp;
            data[0] = u32HHtou8(protocol_task.heard_cnt);
            data[1] = u32MHtou8(protocol_task.heard_cnt);
            data[2] = u32MLtou8(protocol_task.heard_cnt);
            data[3] = u32LLtou8(protocol_task.heard_cnt);

            protocol_bsp_protocol_frame_send(PRO_CMD_HEARTBEAT,data,4);
        break;
        default:break;
    }
}



static void protocol_run(void)
{
    u16 length=0;
    u8 pro_buff[256];
    if(0 == systick_get_difference_assign(&protocol_task.tick,Tnms(100)))
		return ;
    length = protocol_bsp_protocol_frame_get(pro_buff,sizeof(pro_buff));
    if(length>0)
    {
        protocol_process(pro_buff);
    }

}
static void protocol_main_run(void)
{
    switch (sys_task_state_get(TASKID_PROTOCOL))
    {
        case TASK_STAT_FREE:
        case TASK_STAT_POWER_ON:
        case TASK_STAT_INITIAL:
            sys_task_state_set(TASKID_PROTOCOL, TASK_STAT_RUN);
            break;
        case TASK_STAT_RUN:
            protocol_run();
            break;
        case TASK_STAT_UNINITIAL:
            sys_task_state_set(TASKID_PROTOCOL, TASK_STAT_POWER_OFF);
            break;
        case TASK_STAT_POWER_OFF:
        case TASK_STAT_SLEEP:

            break;
        default:
            sys_task_state_set(TASKID_PROTOCOL, TASK_STAT_POWER_ON);
            break;
    }

}
static void protocol_peripheral_sleep(void)
{
    protocol_bsp_uninit();
}
static void protocol_message_process(E_DATAID DatID, const u32 data)
{
	switch(DatID)
	{
		default:break;
	}
}
static void protocol_variable_init(void)
{
    protocol_bsp_init();
}



CONSTRUCTOR_DEFAUTL()
void protocol_task_create(void)
{
	struct task_s task = TASK_DEFAULT_INIT();

	task.ID 		= TASKID_PROTOCOL;
	task.state		= TASK_STAT_FREE;
	task.TaskTime	= 0;
	task.run 		= protocol_main_run;
	task.sleep_init = protocol_peripheral_sleep;
	task.msg_process= protocol_message_process;
	task.task_tick 	= NULL;
	task.is_used 	= 1;
	task.task_init =  protocol_variable_init;
	sys_task_add(&task);
}







